<?php

namespace App\Controllers;

use App\Core\Request;
use App\Core\Response;
use App\Models\Grade;

class GradeController
{
    public function index(): void
    {
        $page = (int) Request::get('page', 1);
        $pageSize = (int) Request::get('pageSize', 20);
        
        $filters = [
            'studentId' => Request::get('studentId'),
            'semester' => Request::get('semester')
        ];
        
        $result = Grade::search($filters, $page, $pageSize);
        
        Response::paginate($result['list'], $result['total'], $page, $pageSize);
    }

    public function getByStudent(string $studentId): void
    {
        $grades = Grade::getByStudentId((int) $studentId);
        Response::success($grades);
    }

    public function store(): void
    {
        $data = Request::validate([
            'student_id' => 'required',
            'semester' => 'required',
            'course_name' => 'required',
            'course_code' => 'required',
            'credit' => 'required',
            'score' => 'required'
        ]);
        
        $currentUser = $GLOBALS['current_user'];
        $data['teacher_id'] = $currentUser['id'];
        $data['teacher_name'] = $currentUser['real_name'];
        
        $id = Grade::create($data);
        
        Response::success(['id' => $id], '创建成功', 201);
    }

    public function update(string $id): void
    {
        $gradeId = (int) $id;
        
        if (!Grade::findById($gradeId)) {
            Response::error('成绩记录不存在', 404);
        }
        
        $data = Request::all();
        unset($data['id'], $data['created_at'], $data['updated_at']);
        
        Grade::update($gradeId, $data);
        
        Response::success(null, '更新成功');
    }

    public function destroy(string $id): void
    {
        $gradeId = (int) $id;
        
        if (!Grade::findById($gradeId)) {
            Response::error('成绩记录不存在', 404);
        }
        
        Grade::delete($gradeId);
        
        Response::success(null, '删除成功');
    }
}

